const glob       = require('glob'),
      path       = require('path'),
      conf       = require('../conf/conf'),
      staticFile = require('koa-static'),
      views      = require('koa-views'),
      error      = require('koa-error'),
      bodyparser = require('koa-bodyparser');

module.exports = function (app) {

    const view  = DEVELOP ? conf.source.view : conf.build.view,
          asset = DEVELOP ? conf.source.asset : conf.build.asset;

    app
        .use(bodyparser())
        .use(staticFile(asset)) // 可以直接访问 asset 目录下的静态文件
        .use(views(view, {
            map      : {
                jade: 'jade' // 给 jade 文件指定为 pug 渲染引擎(jade 已改名为 pug)
            },
            extension: 'jade' // render 时可以不用加后缀
        }))
        .use(error({
            engine  : 'jade',
            template: view + '/error.jade'
        }));

    // init all router
    glob(path.resolve(__dirname, '..', 'controller/**/*.js'), function (err, matches) {
        matches.forEach((fileName)=> {
            const router = require(fileName);
            app.use(router.routes()).use(router.allowedMethods());
        })
    });
};